// pages/mealplan/mealplan.js
const app = getApp();
const mealPlanService = require('../../services/mealPlanService');
const userService = require('../../services/userService');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme: '',  // 添加主题数据
    currentWeekText: '',
    weekDays: [],
    currentDayIndex: 0,
    
    // 饮食数据
    breakfastMeals: [],
    lunchMeals: [],
    dinnerMeals: [],
    
    // 营养摄入数据
    breakfastCalories: 0,
    lunchCalories: 0,
    dinnerCalories: 0,
    totalCalories: 0,
    totalProtein: 0,
    totalCarbs: 0,
    totalFat: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'theme-green';
    this.setData({ theme });
    
    this.initWeekDays();
    this.loadMealPlanData();
  },

  /**
   * 初始化周日期
   */
  initWeekDays() {
    const today = new Date();
    
    // 获取本周的周日
    const sunday = new Date(today);
    sunday.setDate(today.getDate() - today.getDay());
    
    // 生成本周的日期
    this.generateWeekDays(sunday);
    
    // 设置当前选中的日期为今天
    this.setData({
      currentDayIndex: today.getDay()
    });
  },
  
  /**
   * 加载饮食计划数据
   */
  loadMealPlanData() {
    return new Promise((resolve) => {
      // 显示加载提示
      wx.showLoading({
        title: '加载中...'
      });
      
      // 获取当前选中日期的完整日期
      const currentDate = this.data.weekDays[this.data.currentDayIndex].fullDate;
      
      // 从服务加载饮食计划数据
      mealPlanService.getMealPlansByDate(currentDate).then(mealPlans => {
        // 整理数据
        const breakfastMeals = [];
        const lunchMeals = [];
        const dinnerMeals = [];
        
        let breakfastCalories = 0;
        let lunchCalories = 0;
        let dinnerCalories = 0;
        let totalProtein = 0;
        let totalCarbs = 0;
        let totalFat = 0;
        
        // 分类处理饮食数据
        mealPlans.forEach(meal => {
          if (meal.type === 'breakfast') {
            breakfastMeals.push(meal);
            breakfastCalories += (meal.calories || 0);
          } else if (meal.type === 'lunch') {
            lunchMeals.push(meal);
            lunchCalories += (meal.calories || 0);
          } else if (meal.type === 'dinner') {
            dinnerMeals.push(meal);
            dinnerCalories += (meal.calories || 0);
          }
          
          totalProtein += (meal.protein || 0);
          totalCarbs += (meal.carbs || 0);
          totalFat += (meal.fat || 0);
        });
        
        const totalCalories = breakfastCalories + lunchCalories + dinnerCalories;
        
        // 更新数据
        this.setData({
          breakfastMeals,
          lunchMeals,
          dinnerMeals,
          breakfastCalories,
          lunchCalories,
          dinnerCalories,
          totalCalories,
          totalProtein,
          totalCarbs,
          totalFat
        });
        
        wx.hideLoading();
        resolve();
      }).catch(err => {
        console.error('加载饮食计划数据失败', err);
        wx.hideLoading();
        
        wx.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
        
        resolve();
      });
    });
  },
  
  /**
   * 切换到上一周
   */
  previousWeek() {
    // 获取当前周的起始日期
    const firstDay = new Date(this.data.weekDays[0].fullDate);
    
    // 向前推一周
    firstDay.setDate(firstDay.getDate() - 7);
    
    // 更新整周的日期
    this.generateWeekDays(firstDay);
    
    // 默认选中周一
    this.setData({
      currentDayIndex: 1
    });
    
    // 重新加载该周的饮食计划
    this.loadMealPlanData();
  },
  
  /**
   * 切换到下一周
   */
  nextWeek() {
    // 获取当前周的起始日期
    const firstDay = new Date(this.data.weekDays[0].fullDate);
    
    // 向后推一周
    firstDay.setDate(firstDay.getDate() + 7);
    
    // 更新整周的日期
    this.generateWeekDays(firstDay);
    
    // 默认选中周一
    this.setData({
      currentDayIndex: 1
    });
    
    // 重新加载该周的饮食计划
    this.loadMealPlanData();
  },
  
  /**
   * 根据起始日期生成一周的日期
   */
  generateWeekDays(startDate) {
    const weekDays = [];
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    
    // 确保startDate是周日
    const dayOfWeek = startDate.getDay();
    if (dayOfWeek !== 0) {
      startDate.setDate(startDate.getDate() - dayOfWeek);
    }
    
    // 生成一周的日期
    for (let i = 0; i < 7; i++) {
      const date = new Date(startDate);
      date.setDate(startDate.getDate() + i);
      
      const month = date.getMonth() + 1;
      const day = date.getDate();
      
      weekDays.push({
        name: dayNames[i],
        date: `${month}/${day}`,
        fullDate: `${date.getFullYear()}-${month}-${day}`
      });
    }
    
    // 设置当前周的文本
    const firstDate = weekDays[0].date;
    const lastDate = weekDays[6].date;
    
    this.setData({
      weekDays,
      currentWeekText: `${firstDate} - ${lastDate}`
    });
  },
  
  /**
   * 切换日期
   */
  switchDay(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentDayIndex: index
    });
    // 加载该天的饮食计划
    this.loadMealPlanData();
  },
  
  /**
   * 导航到餐品详情页
   */
  navigateToMealDetail(e) {
    const id = e.currentTarget.dataset.id;
    // 从当前所有餐品中找到对应的餐品数据
    const meal = [...this.data.breakfastMeals, ...this.data.lunchMeals, ...this.data.dinnerMeals]
      .find(item => item._id === id);
    
    if (!meal) {
      wx.showToast({
        title: '未找到菜品信息',
        icon: 'none'
      });
      return;
    }
    console.log(meal);

    // 跳转到菜品详情页
    wx.navigateTo({
      url: `/pages/dish-detail/dish-detail?dishId=${meal.dishId}&kitchenId=${meal.kitchenId}`
    });
  },
  
  /**
   * 添加餐品
   */
  addMeal(e) {
    const mealType = e.currentTarget.dataset.type;
    
    // 保存当前选择的餐食类型
    this.setData({
      currentMealType: mealType
    });
    
    wx.showActionSheet({
      itemList: ['从我的厨房选择', '浏览推荐菜单', '自定义餐品'],
      success: (res) => {
        if (!res.cancel) {
          if (res.tapIndex === 0) {
            // 从我的厨房选择
            wx.navigateTo({
              url: '/pages/kitchen-list/kitchen-list?from=mealplan&mealType=' + mealType,
              events: {
                // 监听选择菜品的事件
                selectDish: (dish) => {
                  this.addDishToMealPlan(dish, mealType);
                }
              }
            });
          } else if (res.tapIndex === 1) {
            // 浏览推荐菜单
            wx.navigateTo({
              url: '/pages/discover/discover?from=mealplan&mealType=' + mealType
            });
          } else if (res.tapIndex === 2) {
            // 自定义餐品
            this.createCustomMeal(mealType);
          }
        }
      }
    });
  },
  
  /**
   * 将选择的菜品添加到饮食计划中
   */
  addDishToMealPlan(dish, mealType) {
    // 显示加载提示
    wx.showLoading({
      title: '添加中...'
    });
    
    // 获取当前选中日期
    const currentDate = this.data.weekDays[this.data.currentDayIndex].fullDate;
    
    // 构建餐品数据
    const meal = {
      name: dish.name,
      image: dish.image || '/imgs/chef-hat.svg',
      calories: dish.calories || 0,
      protein: dish.nutrition?.protein || 0,
      carbs: dish.nutrition?.carbs || 0,
      fat: dish.nutrition?.fat || 0,
      date: currentDate,
      type: mealType,
      dishId: dish._id,
      kitchenId: dish.kitchenId
    };
    
    // 使用服务添加饮食计划
    mealPlanService.addMealPlan(meal).then(result => {
      if (result) {
        console.log('成功添加饮食计划:', result);
        
        // 获取当前餐食类型的餐品列表
        let meals = [];
        let caloriesSum = 0;
        
        if (mealType === 'breakfast') {
          meals = [...this.data.breakfastMeals, result];
          caloriesSum = this.data.breakfastCalories + (result.calories || 0);
          
          this.setData({
            breakfastMeals: meals,
            breakfastCalories: caloriesSum
          });
        } else if (mealType === 'lunch') {
          meals = [...this.data.lunchMeals, result];
          caloriesSum = this.data.lunchCalories + (result.calories || 0);
          
          this.setData({
            lunchMeals: meals,
            lunchCalories: caloriesSum
          });
        } else if (mealType === 'dinner') {
          meals = [...this.data.dinnerMeals, result];
          caloriesSum = this.data.dinnerCalories + (result.calories || 0);
          
          this.setData({
            dinnerMeals: meals,
            dinnerCalories: caloriesSum
          });
        }
        
        // 计算新的总卡路里和营养数据
        this.setData({
          totalCalories: this.data.totalCalories + (result.calories || 0),
          totalProtein: this.data.totalProtein + (result.protein || 0),
          totalCarbs: this.data.totalCarbs + (result.carbs || 0),
          totalFat: this.data.totalFat + (result.fat || 0)
        });
        
        wx.hideLoading();
        
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
      } else {
        wx.hideLoading();
        
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('添加饮食计划失败', err);
      wx.hideLoading();
      
      wx.showToast({
        title: '添加失败',
        icon: 'none'
      });
    });
  },
  
  /**
   * 保存饮食计划数据
   */
  saveMealPlanData(meal) {
    // 使用饮食计划服务保存数据
    mealPlanService.addMealPlan(meal).then(result => {
      if (result) {
        console.log('保存饮食计划成功', result);
      } else {
        console.error('保存饮食计划失败');
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('保存饮食计划失败', err);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    });
  },
  
  /**
   * 创建自定义餐品
   */
  createCustomMeal(mealType) {
    wx.showToast({
      title: '自定义餐品功能开发中',
      icon: 'none'
    });
    // 实际开发中，这里可以弹出一个模态框让用户输入自定义餐品的信息
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查主题是否有变化
    const theme = wx.getStorageSync('theme');
    if (theme !== this.data.theme) {
      this.setData({ theme });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 重新加载当前日期的饮食计划
    this.loadMealPlanData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的饮食计划',
      path: '/pages/mealplan/mealplan'
    };
  },

  /**
   * 删除餐品
   */
  deleteMeal(e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个餐品吗？',
      success: (res) => {
        if (res.confirm) {
          // 使用服务删除饮食计划
          mealPlanService.deleteMealPlan(id).then(success => {
            if (success) {
              // 移除页面数据中的餐品
              let meals = [];
              let caloriesSum = 0;
              
              // 获取被删除的餐品数据，用于计算营养值变化
              let deletedMeal = null;
              
              if (type === 'breakfast') {
                deletedMeal = this.data.breakfastMeals.find(item => item._id === id);
                meals = this.data.breakfastMeals.filter(item => item._id !== id);
                caloriesSum = meals.reduce((sum, item) => sum + (item.calories || 0), 0);
                
                this.setData({
                  breakfastMeals: meals,
                  breakfastCalories: caloriesSum
                });
              } else if (type === 'lunch') {
                deletedMeal = this.data.lunchMeals.find(item => item._id === id);
                meals = this.data.lunchMeals.filter(item => item._id !== id);
                caloriesSum = meals.reduce((sum, item) => sum + (item.calories || 0), 0);
                
                this.setData({
                  lunchMeals: meals,
                  lunchCalories: caloriesSum
                });
              } else if (type === 'dinner') {
                deletedMeal = this.data.dinnerMeals.find(item => item._id === id);
                meals = this.data.dinnerMeals.filter(item => item._id !== id);
                caloriesSum = meals.reduce((sum, item) => sum + (item.calories || 0), 0);
                
                this.setData({
                  dinnerMeals: meals,
                  dinnerCalories: caloriesSum
                });
              }
              
              // 如果找到被删除的餐品，则更新总营养摄入
              if (deletedMeal) {
                this.setData({
                  totalCalories: this.data.totalCalories - (deletedMeal.calories || 0),
                  totalProtein: this.data.totalProtein - (deletedMeal.protein || 0),
                  totalCarbs: this.data.totalCarbs - (deletedMeal.carbs || 0),
                  totalFat: this.data.totalFat - (deletedMeal.fat || 0)
                });
              } else {
                // 如果没找到，则重新加载全部数据
                this.loadMealPlanData();
              }
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('删除饮食计划失败', err);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          });
        }
      }
    });
  }
})